//
//  OAuthViewController.swift
//  weibo
//
//  Created by 杨晨 on 16/3/9.
//  Copyright © 2016年 杨晨. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {

    let  webView = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()

        setNavBar()
        
        view.backgroundColor = UIColor.whiteColor()
        
        loadOAuthPage()
    }

    private func setNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    }
    
    func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewWillDisappear(animated: Bool) {
        
        SVProgressHUD.dismiss()
    }
    
    override func loadView() {
        
        super.loadView()
        view = webView
        webView.delegate = self
        view.opaque = false
        
    }
    
    private func loadOAuthPage(){
       //urlstring
        let urlString = "https://api.weibo.com/oauth2/authorize?"+"client_id=1918764785"+"&redirect_uri=http://www.itcast.cn"
       //nsurl
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        webView.scalesPageToFit = true
        
        webView.paginationMode = UIWebPaginationMode.TopToBottom
    }
    
    
}
//code=4ae416938fcfb71162f42de4818edec2
//拓展
extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    //准备加载页面是跳转,默认为YES 可以在页面跳转时候截取
    //在这个协议之中,可以检测webview每次加载新的页面发起的网络请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        //absoluteString 绝对路径 如果是空 不加载
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        
        if urlString.containsString("code"){
            //要获取code 通过code获得token
            
            print(urlString)
            
            guard let query = request.URL?.query else{
                
                return false
            }
            
           let codeStr = "code="
            
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            accesstoken(code)
            
            return false
        }
      
        
        
        return true
       
        
    }
    
    
    private func accesstoken(code:String){
        //发起网络请求
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id":1918764785 ,"client_secret":"1bf23d2767c321fb25050b3b8a91bd19","grant_type":"authorization_code","code":code,"redirect_uri":"http://www.itcast.cn"]
        
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (task , result) -> Void in
//            print("============================================================")
//            
//            //获得token等
//            print(result)
//            print("============================================================")
            //获取token
            guard let dic = result as? [String : AnyObject] else{
                SVProgressHUD.showErrorWithStatus("输入错误")
                
                return
            }
            
            //将字典信息传过去(里面包含了token等信息)
            self.loadUserInfo(dic)
            let token = dic["access_token"]
            //获取到用户接口访问权限后 使用token去获取用户信息
            
            
            
            }) { (task , error ) -> Void in
                
           // print(error)
        }
        
    }
    //dic 包含的是token等信息
    //dict 包含的是通过token访问和得到的用户信息
    
    //获取token后加载用户信息
    private func loadUserInfo(dic: [String : AnyObject]){
       
        //强转成string
        let token = dic["access_token"] as! String
        let uid = dic["uid"] as! String
        
        print("????????????????????????")
        print(token)
        print(uid)
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
         let AFN = AFHTTPSessionManager()
        //在字典中不能添加nil
        
        let parameters = ["access_token":token,"uid":uid]
    
        
        
         AFN.GET(urlString, parameters: parameters, progress: nil, success: { (task, result) -> Void in
            //获取用户数据(字典)
            guard var userInfoDic = result as? [String : AnyObject] else {
                
                SVProgressHUD.showErrorWithStatus("信息错误")
                return
            }
            
        //合并字典
            
            
            
            for (k,v) in dic {
                
                //将字典dic的中的键和值取出来放到字典dict中, 获得合并后的字典dict
                userInfoDic[k] = v
      //          存入沙盒,沙盒中不能够存入空值
//                print("========================")
//                print(userInfoDic)
//                print("=========================")
//                
               
                
                
               // NSUserDefaults.standardUserDefaults().setObject(dict, forKey: "www.itcast.cn")
                
                
            }
            //bug不能再循环里面赋值
            userAccount.shareAccount.saveUserInfo(userInfoDic)
            
            
            }) { (task, error) -> Void in
             print(error)
        }
        
    }
    
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
}
